<?php
namespace Account\Controller;

use Common\Controller\ApiController;

class ClinichistoryController extends ApiController
{
    public function store()
    {
        $input = $this->request();
        $user = $this->user;
        $isPublic = filter($input['is_public'], 'F');
        $data = [
            'user_id' => $user['id'],
            'content' => $input['content'],
            'delete_time' => 0,
            'is_public' => $isPublic,
        ];
        $mClinichistory = D('Clinichistory');
        if ($mClinichistory->create($data)) {
            $mClinichistory->add();
            $this->createdResponse();
        } else {
            $this->errorResponse(30000, $mClinichistory->getError());
        }
    }

    public function update()
    {
        $id = I('get.id');
        $input = $this->request();
        $user = $this->user;
        $clinichistory = D('Clinichistory')->where(['user_id' => $user['id'], 'id' => $id])->find();
        if ($clinichistory) {
            $data = [
                'id' => $id,
                'content' => $input['content'],
            ];
            $mClinichistory = D('Clinichistory');
            if ($mClinichistory->create($data)) {
                $mClinichistory->save();
                $this->modifySuccessResponse();
            } else {
                $this->errorResponse(30000, $mClinichistory->getError());
            }
        } else {
            $this->errorResponse(30023);
        }
    }



    public function index()
    {
        $input = $this->request();
        $page = (int)filter($input['page'], 1);
        $perPage = (int)filter($input['per_page'], 10);
        $user = $this->user;

        $where = [];
        $where['user_id'] = $user['id'];
        $count = D('Clinichistory')->where($where)->count();
        $clinichistories = D('Clinichistory')
            ->where($where)
            ->page($page, $perPage)
            ->select();
        $clinichistories = transform('Clinichistory', 'detail', $clinichistories);
        $pagination = pagination($count, $perPage, $page);
        $this->response($clinichistories, $pagination);
    }

    public function showDetail($id)
    {
        $user = $this->user;
        $clinichistory = D('Clinichistory')->where(['id' => $id])->find();
        if ($clinichistory) {
            $clinichistory['is_creator'] = $clinichistory['user_id'] == $user['id'] ? 'T' : 'F';
            $clinichistory = transform('Clinichistory', 'detail', $clinichistory);
            $this->response($clinichistory);
        } else {
            $this->errorResponse(30023);
        }
        
    }

}
